package com.tjetc.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;

@Component
@Slf4j
@ServerEndpoint("/websocket") //暴露的ws应用的路径
public class WebSocketController {
    private static Session session;

    /**
     * 客户端与服务端连接成功
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        /*
            do something for onOpen
            与当前客户端连接成功时
         */
        log.info(new Date().toLocaleString(),
                session.getId());
        this.session=session;
    }

    /**
     * 客户端与服务端连接关闭
     * @param session
     */
    @OnClose
    public void onClose(Session session){
        /*
            do something for onClose
            与当前客户端连接关闭时
         */
        log.info(new Date().toLocaleString(),
                session.getId());
    }

    /**
     * 客户端与服务端连接异常
     * @param error
     * @param session
     */
    @OnError
    public void onError(Throwable error,Session session) {
        /*
            do something for onError
            与当前客户端连接异常时
         */
        error.printStackTrace();
    }


    public static void sendMessageToClient(String orderId) {
        System.out.println("web"+orderId);
        session.getAsyncRemote().sendText(orderId);
    }
}



